// AI Video Generation Configuration Service
// This service manages AI API tokens and configuration settings specifically for video generation

const AI_VIDEO_CONFIG_KEY = 'aiVideoConfig';
const DEFAULT_CONFIG = {
  apiToken: '',
  provider: 'aliyun', // aliyun, runway, stable-video, pika, etc.
  model: 'wanx-v1', // default model for video generation
  endpoint: 'https://dashscope.aliyuncs.com/api/v1', // Aliyun DashScope endpoint
  maxTokens: 4000,
  temperature: 0.7,
  isFree: false // Flag to indicate if this is a free service
};

/**
 * Get AI Video configuration from localStorage
 * @returns {Object} AI Video configuration object
 */
export const getAIVideoConfig = () => {
  try {
    const config = localStorage.getItem(AI_VIDEO_CONFIG_KEY);
    return config ? { ...DEFAULT_CONFIG, ...JSON.parse(config) } : DEFAULT_CONFIG;
  } catch (error) {
    console.error('Error getting AI Video config:', error);
    return DEFAULT_CONFIG;
  }
};

/**
 * Save AI Video configuration to localStorage
 * @param {Object} config - AI Video configuration object
 * @returns {boolean} Success status
 */
export const saveAIVideoConfig = (config) => {
  try {
    const currentConfig = getAIVideoConfig();
    const newConfig = { ...currentConfig, ...config };
    localStorage.setItem(AI_VIDEO_CONFIG_KEY, JSON.stringify(newConfig));
    return true;
  } catch (error) {
    console.error('Error saving AI Video config:', error);
    return false;
  }
};

/**
 * Check if AI Video API token is configured
 * @returns {boolean} Token status
 */
export const isVideoTokenConfigured = () => {
  const config = getAIVideoConfig();
  return !!config.apiToken;
};

/**
 * Get API headers for AI Video requests
 * @returns {Object} Headers object
 */
export const getVideoAPIHeaders = () => {
  const config = getAIVideoConfig();
  return {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${config.apiToken}`
  };
};

/**
 * Validate API token format for video services (basic validation)
 * @param {string} token - API token to validate
 * @returns {boolean} Validation result
 */
export const validateVideoToken = (token) => {
  if (!token || typeof token !== 'string') {
    return false;
  }
  
  // For Aliyun DashScope tokens (starts with 'sk-')
  if (token.startsWith('sk-') && token.length > 20) {
    return true;
  }
  
  // For Aliyun AccessKey (starts with 'LTAI')
  if (token.startsWith('LTAI') && token.length > 20) {
    return true;
  }
  
  // For Runway tokens (starts with 'rw-')
  if (token.startsWith('rw-') && token.length > 20) {
    return true;
  }
  
  // For Stable Video tokens (starts with 'sv-')
  if (token.startsWith('sv-') && token.length > 20) {
    return true;
  }
  
  // For Pika tokens (starts with 'pk-')
  if (token.startsWith('pk-') && token.length > 20) {
    return true;
  }
  
  // For Hugging Face tokens (starts with 'hf_')
  if (token.startsWith('hf_') && token.length > 20) {
    return true;
  }
  
  // For other providers, just check if it's a reasonable length
  return token.length > 10;
};

/**
 * Reset AI Video configuration to defaults
 * @returns {boolean} Success status
 */
export const resetAIVideoConfig = () => {
  try {
    localStorage.setItem(AI_VIDEO_CONFIG_KEY, JSON.stringify(DEFAULT_CONFIG));
    return true;
  } catch (error) {
    console.error('Error resetting AI Video config:', error);
    return false;
  }
};

/**
 * Get available AI Video providers (including free/open source options)
 * @returns {Array} Array of provider objects
 */
export const getAvailableVideoProviders = () => {
  return [
    {
      id: 'aliyun',
      name: '阿里云通义万象',
      description: '阿里云推出的AI视频生成服务，支持高质量视频创作',
      isFree: false,
      models: [
        { id: 'wanx-v1', name: '通义万象V1', description: '高质量视频生成模型' },
        { id: 'wanx-image-to-video', name: '图像转视频', description: '将静态图像转换为动态视频' }
      ],
      endpoint: 'https://dashscope.aliyuncs.com/api/v1',
      website: 'https://dashscope.aliyun.com',
      tokenHelp: '从阿里云DashScope控制台获取API-KEY'
    },
    {
      id: 'runway',
      name: 'Runway ML',
      description: 'Professional video generation with Gen-2',
      isFree: false,
      models: [
        { id: 'gen-2', name: 'Gen-2', description: 'Text-to-video and image-to-video' },
        { id: 'gen-1', name: 'Gen-1', description: 'Video-to-video with style transfer' }
      ],
      endpoint: 'https://api.runwayml.com/v1',
      website: 'https://runwayml.com',
      tokenHelp: 'Get your API key from Runway ML dashboard'
    },
    {
      id: 'stable-video',
      name: 'Stable Video Diffusion',
      description: 'Open source video generation by Stability AI',
      isFree: true,
      models: [
        { id: 'svd-xt', name: 'SVD-XT', description: 'High-quality video generation' },
        { id: 'svd', name: 'SVD', description: 'Standard video generation' }
      ],
      endpoint: 'https://api.stability.ai/v1',
      website: 'https://stability.ai',
      tokenHelp: 'Get your free API key from Stability AI platform'
    },
    {
      id: 'pika',
      name: 'Pika Labs',
      description: 'AI video generation and editing',
      isFree: false,
      models: [
        { id: 'pika-1.0', name: 'Pika 1.0', description: 'Latest video generation model' },
        { id: 'pika-0.9', name: 'Pika 0.9', description: 'Previous generation model' }
      ],
      endpoint: 'https://api.pika.art/v1',
      website: 'https://pika.art',
      tokenHelp: 'Get your API key from Pika Labs dashboard'
    },
    {
      id: 'huggingface',
      name: 'Hugging Face',
      description: 'Open source models and spaces',
      isFree: true,
      models: [
        { id: 'zeroscope-v2-xl', name: 'ZeroScope V2 XL', description: 'Open source video generation' },
        { id: 'damo-text-to-video', name: 'DAMO Text-to-Video', description: 'Alibaba\'s video model' },
        { id: 'videogen', name: 'VideoGen', description: 'Microsoft\'s video generation model' }
      ],
      endpoint: 'https://api-inference.huggingface.co/models',
      website: 'https://huggingface.co',
      tokenHelp: 'Get your free API token from Hugging Face settings'
    },
    {
      id: 'replicate',
      name: 'Replicate',
      description: 'Platform for running AI models',
      isFree: false,
      models: [
        { id: 'stable-video-diffusion', name: 'Stable Video Diffusion', description: 'Open source video model' },
        { id: 'zeroscope-v2-xl', name: 'ZeroScope V2 XL', description: 'High-quality video generation' }
      ],
      endpoint: 'https://api.replicate.com/v1',
      website: 'https://replicate.com',
      tokenHelp: 'Get your API token from Replicate dashboard'
    }
  ];
};

/**
 * Get models for a specific video provider
 * @param {string} providerId - Provider ID
 * @returns {Array} Array of model objects
 */
export const getVideoProviderModels = (providerId) => {
  const providers = getAvailableVideoProviders();
  const provider = providers.find(p => p.id === providerId);
  return provider ? provider.models : [];
};

/**
 * Get free video providers
 * @returns {Array} Array of free provider objects
 */
export const getFreeVideoProviders = () => {
  return getAvailableVideoProviders().filter(provider => provider.isFree);
};